package com.easpeed.comon.socket_tool

import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress


/**
 * Created by bigyu on 2025-06-26 18:20
 * com.easpeed.comon.socket
 */
class SocketServer {

    private val handler = Handler(Looper.getMainLooper())

    private var server: WebSocketServer? = null

    private var port: String? = null
    private var isStart = false
    val TAG = "SocketServer"

    fun startServer(port: String) {
        this.port = port
        if (isServerStart()) {
            Log.e(TAG, "startServer: 服务端已启动")

            return
        }
        if (port.isEmpty() || !TextUtils.isDigitsOnly(port)) {
            Log.e(TAG, "startServer: 端口号错误")
            return
        }

        Log.e(TAG, "startServer: 正在启动服务端 $port")
        server = object : WebSocketServer(InetSocketAddress(port.toInt())) {
            override fun onOpen(conn: WebSocket, handshake: ClientHandshake?) {
                senLog("连接成功：" + conn.remoteSocketAddress)
                Log.d("WebSocket", "连接成功：" + conn.remoteSocketAddress)
                conn.send("欢迎连接 WebSocket！")
            }

            override fun onClose(conn: WebSocket?, code: Int, reason: String, remote: Boolean) {
                senLog("连接关闭：$reason")
                Log.d("WebSocket", "连接关闭：$reason")
            }


            override fun onMessage(conn: WebSocket, message: String) {
                Log.d("WebSocket", "收到消息：$message")
                senLog(message)
                conn.send("服务器收到：$message") // Echo 回传
            }

            override fun onError(conn: WebSocket?, ex: Exception) {
                Log.e("WebSocket", "出错：" + ex.message)
            }

            override fun onStart() {
                connectChange(true, "服务启动")
                senLog("WebSocket 服务端启动")
                isStart = true
                Log.d("WebSocket", "WebSocket 服务端启动")
            }


        }

        server?.start()
    }



    fun connectChange(isConnect: Boolean, msg: String?) {
        handler.post {
            onConnectListener?.invoke(isConnect, msg)
        }
    }

    fun senLog(msg: String?) {
        handler.post {
            onMessageListener?.invoke(msg)
        }
    }
    private var onMessageListener: ((message: String?) -> Unit)? = null
    fun setOnMessageListener(listener: (message: String?) -> Unit) {
        this.onMessageListener = listener
    }

    private var onConnectListener: ((isConnect: Boolean, msg: String?) -> Unit)? = null
    fun setServerStartListener(listener: (isStart: Boolean, msg: String?) -> Unit) {
        this.onConnectListener = listener
    }

    fun stopServer() {
        if (server != null) {
            connectChange(false, "服务关闭")
            isStart = false
            server?.stop()
            senLog("WebSocket 服务端关闭")
            Log.d("WebSocket", "WebSocket 服务端关闭")
        }
    }

    fun isServerStart(): Boolean {
        return server != null && isStart
    }

    fun getPort(): String {

        return port.toString()
    }


}